package com.shrw.duke.serialport.port.p;

import com.shrw.duke.serialport.common.PortArg;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import serial.utils.SerialPort;

/**
 * IData手持机串口操作
 * @author: ZengZhenHua
 * @date: 2018/12/20
 * @email: cengzhenghua@163.com
 */
public class IData95vPort extends Port {
    private SerialPort mPort;

    @Override
    public void initPort() {
        mPort = new SerialPort();
    }

    @Override
    public boolean isOpen() {
        return mPort == null ? false : mPort.isOpen(mPort.getFileDescriptor());
    }

    @Override
    public FileDescriptor open() throws SecurityException, IOException {
        if (!mPort.isOpen(mPort.getFileDescriptor())) {
            String path = PortArg.device;
            int baudrate = Integer.decode(PortArg.baudrate);
            int nbits = Integer.decode(PortArg.bits);
            int nstop = Integer.decode(PortArg.nstop);
            char cVerify = PortArg.cverify.charAt(0);
            //上电
            SerialPort.SetIoState(PortArg.IOCTRL_PMU_BARCODE_ON);
            SerialPort.SetIoState(PortArg.IOCTRL_PMU_RFID_ON);

            //打开串口
            return mPort.open(new File(path), baudrate, nbits, cVerify, nstop, 0);
        }
        return mPort.getFileDescriptor();
    }

    @Override
    public void close() {
        if (mPort.isOpen(mPort.getFileDescriptor())) {
            mPort.close();
            SerialPort.SetIoState(PortArg.IOCTRL_PMU_BARCODE_OFF);
            SerialPort.SetIoState(PortArg.IOCTRL_PMU_RFID_OFF);
        }
    }

    @Override
    public FileInputStream getFileInputStream(FileDescriptor fd) {
        return mPort == null ? null : new FileInputStream(mPort.getFileDescriptor());
    }

    @Override
    public FileOutputStream getFileOutputStream(FileDescriptor fd) {
        return mPort == null ? null : new FileOutputStream(mPort.getFileDescriptor());
    }

    @Override
    public void destroy() {
        close();
        mPort = null;
    }
}
